<template>
  <div class="codeBody" @mouseenter="hover = true" @mouseleave="hover = false">
    <i
      class="el-icon-document-copy iconPosition"
      @click="copyCod"
      v-show="hover"
    ></i>
    <code id="copyArea">
      <slot></slot>
    </code>
  </div>
</template>
<script>
export default {
  name: "copyColu",
  data() {
    return {
      hover: false,
    };
  },
  methods: {
    copyCod() {
      var value = document.getElementById("copyArea");
      var oInput = document.createElement("input");
      oInput.value = value.innerText;
      document.body.appendChild(oInput);
      oInput.select();
      let bool = document.execCommand("Copy");
      try {
        if (bool) {
          this.$message({
            type: "success",
            message: "复制成功",
          });
        } else {
          this.$message({
            type: "error",
            message: "复制失败",
          });
        }
      } catch (err) {
        return err;
      }
      oInput.remove();
    },
  },
};
</script>
<style scoped>
#copyArea{
    word-wrap: break-word;
    font-size: 15px;
}
.codeBody {
  width: 40%;
  margin: 10px auto;
  background-color: #f6f6f6;
  padding: 20px 20px;
  position:relative;
  margin-bottom: 10px;
  border-radius: 5px;
}
.iconPosition {
    position: absolute;
    top: -6px;
    right: 0;
}
.el-icon-document-copy:hover {
  cursor: pointer;
}
</style>
